package com.zx.disneyholidays.net;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONObject;
import com.tencent.mmkv.MMKV;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.Map;
import java.util.Stack;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttp;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

public class HttpUtils {

    private final static String DOMAIN = "http://dsnqrreplace.dev.zhangxinkeji.com/";

    private HttpUtils() {

    }

    public static HttpUtils instance = new HttpUtils();


    private final OkHttpClient okhttpClient = new OkHttpClient.Builder().build();


    public void httpGet(String url, Map<String, String> params, ResponseCallBack callBack) {
        String token = MMKV.defaultMMKV().decodeString("token", "");
        Request request = new Request.Builder()
                .url(DOMAIN + handleGetUrl(url, params))
                .addHeader("Authorization", token == null ? "" : token)
                .build();
        okhttpClient.newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        handleFailure(-1, "网络加载失败", callBack);
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        handleResponse(response, callBack);
                    }
                });
    }


    private String handleGetUrl(String url, Map<String, String> params) {
        if (params == null || params.size() == 0) {
            return url;
        }

        int i = 0;
        for (String key : params.keySet()) {
            if (i == 0) {
                url = url + "?" + key + "=" + params.get(key);
            } else {
                url = url + "&" + key + "=" + params.get(key);
            }
            i++;
        }

        return url;
    }

    public void httpPostWithMulti(String url, String filePath, ResponseCallBack callBack) {
        String token = MMKV.defaultMMKV().decodeString("token", "");
        File file = new File(filePath);
        RequestBody fileBody = RequestBody.create(MediaType.get("image/jpeg"), file); //将file转换成RequestBody文件
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", "temp.png", fileBody)
                .build();
        Request request = new Request.Builder()
                .url(DOMAIN + url)
                .addHeader("Authorization", token == null ? "" : token)
                .post(requestBody)
                .build();


        okhttpClient.newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        handleFailure(-1, "网络加载失败", callBack);
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        handleResponse(response, callBack);
                    }
                });
    }


    public void httpPost(String url, String json, ResponseCallBack callBack) {
        String token = MMKV.defaultMMKV().decodeString("token", "");
        RequestBody body = RequestBody.create(MediaType.get("application/json; charset=utf-8"), json);
        Request request = new Request.Builder()
                .url(DOMAIN + url)
                .addHeader("Authorization", token == null ? "" : token)
                .post(body)
                .build();


        okhttpClient.newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        handleFailure(-1, "网络加载失败", callBack);
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        handleResponse(response, callBack);
                    }
                });
    }


    public void handleResponse(Response response, ResponseCallBack callBack) {
        if (response.body() == null) {
            new Handler(Looper.getMainLooper()).post(() -> callBack.onError(-1, "数据异常"));
            return;
        }

        try {
            BaseResponse result = JSONObject.parseObject(response.body().string(), BaseResponse.class);
            new Handler(Looper.getMainLooper()).post(() -> callBack.onSuccess(result));
        } catch (Exception e) {
            new Handler(Looper.getMainLooper()).post(() -> callBack.onError(-1, "数据异常"));
            e.printStackTrace();
        }
    }


    void handleFailure(int error, String msg, ResponseCallBack callBack) {
        new Handler(Looper.getMainLooper()).post(() -> callBack.onError(error, msg));
    }
}
